﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using Tebbee.UI.Client.AccountSer;

namespace Tebbee.UI.Client.Controllers.MemberApi
{
    public class MemberProfileController : ApiController
    {
        private readonly AccountSerClient db = new AccountSerClient();
        /// <summary>
        /// Function return current member's profile
        /// </summary>
        /// <returns></returns>
        public Member_GetByUserName_Result GetUserProfile()
        {
            //Get current user name of member logged
            var userName = HttpContext.Current.User.Identity.Name;
            return db.GetMemberByUserName(userName);
        }

        public Member_GetByMemId_Result GetMemProfile(int id)
        {
            //Get current user name of member logged
            return db.GetMemberById(id);
        }

        /// <summary>
        /// Function return point list of current member
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public HttpResponseMessage GetPointList(int id)
        {
            var userName = HttpContext.Current.User.Identity.Name;
            int totalPage = 0; //Initial variable to get totalpage after get data from server
            IEnumerable<Member_PointList_Result> list = db.GetPointList(out totalPage, userName, id);
            //Return list point and total page to client
            return Request.CreateResponse(HttpStatusCode.OK, new { list, totalPage });
        }

        /// <summary>
        /// Function return subcribe list of current member
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public HttpResponseMessage GetSubcribeList(int id)
        {
            var userName = HttpContext.Current.User.Identity.Name;
            int totalPage = 0; //Initial variable to get totalpage after get data from server
            IEnumerable<Member_SubcribeList_Result> list = db.GetSubcribeList(out totalPage, userName, id);
            //Return list point and total page to client
            return Request.CreateResponse(HttpStatusCode.OK, new { list, totalPage });
        }

        /// <summary>
        /// Function remove a subcribe member don't need any more
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public HttpResponseMessage RemoveSubcribe(int id)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (db.RemoveSubcribe(id) != 0)
            {
                return Request.CreateResponse(HttpStatusCode.OK, id);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Not Found");
            }
        }

        /// <summary>
        /// Function return exchange logs of current member
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public HttpResponseMessage GetExchangeLog(int id)
        {
            var userName = HttpContext.Current.User.Identity.Name;
            int totalPage = 0; //Initial variable to get totalpage after get data from server
            IEnumerable<Member_ExchangeLog_Result> list = db.GetExchangeLog(out totalPage, userName, id);
            //Return list point and total page to client
            return Request.CreateResponse(HttpStatusCode.OK, new { list, totalPage });
        }

        /// <summary>
        /// Fuction update user profile
        /// </summary>
        /// <param name="mem"></param>
        /// <returns></returns>
        public HttpResponseMessage UpdateProfile(MemberFull mem)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string msg = "";
            mem.UserName = HttpContext.Current.User.Identity.Name;
            int rs = db.EditFullProfilesMember(out msg, mem);
                
            if (rs > 0)
            {
                return Request.CreateResponse(HttpStatusCode.OK, mem);
            }
            else
            {
                HttpError err = new HttpError();
                err.Message = msg;
                if (rs == -1)
                {
                    FormsAuthentication.SignOut();
                }
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, err);
            }
        }

        /// <summary>
        /// Function allow member change password
        /// </summary>
        /// <param name="mem"></param>
        /// <returns></returns>
        public HttpResponseMessage ChangePassword(ChangePassModel mem)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string msg = "";
            mem.UserName = HttpContext.Current.User.Identity.Name;
            if (db.ChangePwd(out msg, mem))
            {
                return Request.CreateResponse(HttpStatusCode.OK, mem);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        /// <summary>
        /// Function change member's avatar
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage ChangeAvatar()
        {
            var httpRequest = HttpContext.Current.Request;

            // Check if files are available
            if (httpRequest.Files.Count > 0)
            {   
                string avatar = "";
                // interate the files and save on the server
                foreach (string file in httpRequest.Files)
                {
                    var userName = HttpContext.Current.User.Identity.Name;
                    var saveFile = httpRequest.Files[file];
                    string [] imgSplit = saveFile.FileName.Split('.');
                    string imgType = imgSplit[imgSplit.Length - 1]; //Get image type

                    //Change new avatar link in server and get link of old avatar, new avatar
                    Member_ChangeAvatar_Result rs = db.ChangeAvatar(userName, imgType);

                    //Check if old avatar is exist in server >> delete
                    if (!string.IsNullOrEmpty(rs.OldAvatar))
                    {
                        var delPath = HttpContext.Current.Server.MapPath(rs.OldAvatar);
                        FileInfo delFile = new FileInfo(delPath);
                        if (delFile.Exists)
                        {
                            File.Delete(delPath);
                        }
                    }
                    //Save new avatar in server
                    var savePath = HttpContext.Current.Server.MapPath(rs.NewAvatar);
                    saveFile.SaveAs(savePath);
                    avatar = rs.NewAvatar.Replace("~", "..");
                }
                return Request.CreateResponse(HttpStatusCode.OK, avatar);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        public String GetCurrentUser()
        {
            return HttpContext.Current.User.Identity.Name;
        }
    }
}
